package com.lab.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Environment;
import android.os.StatFs;

import java.io.File;
import java.io.IOException;

/**
 * 业务相关文件工具类
 * Created by ak
 */
public class DictionaryUtil {

    public static final long BYTES_PER_MB = 1024 * 1024;
    public static final long BYTES_PER_GB = BYTES_PER_MB * 1024;

    @SuppressLint("NewApi")
    public static File getCacheDir(Context context) throws IOException {
        if (context == null) throw new IOException("context is null");
        File file = null;
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            file = getCacheDirInternal(context);
        } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            throw new IOException("external storage is read only");
        } else {
            throw new IOException("external storage is not mounted");
        }
        if (file != null) {
            if (!file.exists()) {
                file.mkdirs();
            }
        } else {
            throw new IOException("can't find a cache dir");
        }
        return file;
    }

    private static File getCacheDirInternal(Context context) {
        File file = null;
        try {
            file = context.getExternalCacheDir();
        } catch (SecurityException se) {
            se.printStackTrace();
            file = new File(Environment
                    .getExternalStorageDirectory()
                    .getAbsolutePath()
                    .concat("/Android/data/" + context.getPackageName()
                            + "/cache/"));
        }
        return file;
    }


    /**
     * 获取文件夹剩余空间大小(字节)
     *
     * @param dir
     * @return
     */
    public static long getAvailableMemory(String dir) {
        StatFs stat = null;
        try {
            stat = new StatFs(dir);
        } catch (IllegalArgumentException e) {
            return 0;
        }
        long blockBytes = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        return availableBlocks * blockBytes;
    }

    /**
     * 获取文件夹总空间大小(字节)
     *
     * @param dir
     * @return
     */
    public static long getAllMemory(String dir) {
        StatFs stat = null;
        try {
            stat = new StatFs(dir);
        } catch (IllegalArgumentException e) {
            return 0;
        }
        long blockBytes = stat.getBlockSize();
        long allBlocks = stat.getBlockCount();
        return allBlocks * blockBytes;
    }

    public static File getSystemPictureDir() {
        File pictureDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File dir = new File(pictureDir.getAbsolutePath().concat("/cuitrip"));
        if (!dir.exists()) dir.mkdirs();
        return dir;
    }
}
